//公共js，主要做表单验证，以及基本方法封装
const utils = {
	isLogin: function(){
		// 判断是否登录
		if(uni.getStorageSync('TOKEN')){
			return true
		} else {
			// uni.showToast({
			// 	title: '请登陆后再试',
			// 	icon: 'none',
			// 	duration: 2000
			// })
			uni.navigateTo({
				url:"/pages/my/login"
			})
			return false
		}
	},
	// 为了防止审核通不过
	// 设定一个时间，在该时间之前隐藏代码
	isHide: function(value) {
		let regTime = new Date('2024/6/11 19:00:00').getTime()
		let currentTime = new Date().getTime()
		return currentTime < regTime
	},
	isNullOrEmpty: function(value) {
		//是否为空
		return (value === null || value === '' || value === undefined) ? true : false;
	},
	trim: function(value) {
		//去空格
		return value.replace(/(^\s*)|(\s*$)/g, "");
	},
	isMobile: function(value) {
		//是否为手机号
		return /^(?:13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{5}(\d{3}|\*{3})$/.test(value);
	},
	isFloat: function(value) {
		//金额，只允许保留两位小数
		return /^([0-9]*[.]?[0-9])[0-9]{0,1}$/.test(value);
	},
	isNum: function(value) {
		//是否全为数字
		return /^[0-9]+$/.test(value);
	},
	isCardNo: function(val) {
		return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(val)
	},
	checkPwd: function(value) {
		//密码为8~20位数字和字母组合
		return /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/.test(value);
	},
	formatNum: function(num) {
		//格式化手机号码
		if (utils.isMobile(num)) {
			num = num.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
		}
		return num;
	},
	rmoney: function(money) {
		//金额格式化
		return parseFloat(money).toFixed(2).toString().split('').reverse().join('').replace(/(\d{3})/g, '$1,')
			.replace(
				/\,$/, '').split('').reverse().join('');
	},

	isUserName: function(name) {
		var reg = /^[a-zA-Z_\u4E00-\u9FA50-9]{2,15}$/
		return reg.test(name)
	},

	isPassword: function(password) {
		var reg = /^[a-zA-Z_0-9.]{6,15}$/
		return reg.test(password)
	},
	//随机生成n位的数据
	randomNum: function(n) {
		let sString = "";
		let strings = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		for (i = 0; i < n; i++) {
			ind = Math.floor(Math.random() * strings.length);
			sString += strings.charAt(ind);
		}
		return sString
	},

	// 生成随机色
	getRandomColor: function() {
		let color = `#${Math.floor(Math.random() * 0xffffff).toString(16)}`
		return color
	},

	/**
	 * @static 时间戳转完整时间
	 * @param {Number} timestamp 时间戳
	 * @param {Number} n 组合选择
	 * @returns
	 * @memberof Tools
	 */
	formatDateIos: function(date, fmt) {
		if (date == null || date == '' || date == undefined)
			return null;
		try {
			//解决ios手机时间格式化NAN问题
			if (typeof(date) == "string" && date.indexOf('-') != -1) {
				date = date.replace(/-/g, '/');
			}
			date = new Date(date);
		} catch (e) {
			date = date;
		}
		fmt = fmt ? fmt : 'yyyy-MM-dd';
		var o = {
			"M+": date.getMonth() + 1, //月份 
			"d+": date.getDate(), //日 
			"H+": date.getHours(), //小时 
			"m+": date.getMinutes(), //分
			"s+": date.getSeconds(), //秒 
			"q+": Math.floor((date.getMonth() + 3) / 3), //季度 
			"S": date.getMilliseconds() //毫秒 
		};
		if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1
			.length));
		for (var k in o)
			if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[
				k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		return fmt;
	},

	formatFullTime: function(timestamp, n = 1) {
		if (String(timestamp).length === 10) {
			timestamp *= 1000
		}
		let date = new Date(timestamp)
		let year = date.getFullYear()
		let month = date.getMonth() + 1
		let day = date.getDate()

		let hour = ''
		if (date.getHours() < 10) {
			hour = '0' + date.getHours()
		} else {
			hour = date.getHours()
		}
		let minute = ''
		if (date.getMinutes() < 10) {
			minute = '0' + date.getMinutes()
		} else {
			minute = date.getMinutes()
		}
		let second = date.getSeconds()
		if (n === 1) return `${year}-${month}-${day} ${hour}:${minute}:${second}`
		if (n === 2) return `${month}-${day}`
		if (n === 3) return `${year}/${month}/${day}`
		if (n === 4) return `${year}-${month}-${day}`
		if (n === 5) return `${year}/${month}/${day} ${hour}:${minute}:00`
		if (n === 6) return `${year}/${month}/${day} ${hour}:${minute}:${second}`
	},

	getCurrentDate: function() {
		var dateTime = new Date();
		var year = dateTime.getFullYear();
		var month = dateTime.getMonth() + 1;
		var day = dateTime.getDate();
		return year + '-' + month + '-' + day
	},

	formatMsgTime: function(timespan) {
		if (String(timespan).length === 10) {
			timespan *= 1000
		}
		var dateTime = new Date(timespan);

		var year = dateTime.getFullYear();
		var month = dateTime.getMonth() + 1;
		var day = dateTime.getDate();
		var hour = dateTime.getHours();
		var minute = dateTime.getMinutes();
		var second = dateTime.getSeconds();
		var now = new Date();
		var now_new = Date.parse(now.toDateString()); //typescript转换写法

		var milliseconds = 0;
		var timeSpanStr;

		milliseconds = now_new - timespan;

		if (milliseconds <= 1000 * 60 * 1) {
			timeSpanStr = '刚刚';
		} else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) {
			timeSpanStr = Math.round((milliseconds / (1000 * 60))) + '分钟前';
		} else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) {
			timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + '小时前';
		} else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) {
			timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前';
		} else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year == now.getFullYear()) {
			timeSpanStr = month + '-' + day + ' ' + hour + ':' + minute;
		} else {
			timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
		}
		return timeSpanStr;
	},
	formatDate: function(formatStr, fdate) {
		//日期格式化
		if (fdate) {
			if (~fdate.indexOf('.')) {
				fdate = fdate.substring(0, fdate.indexOf('.'));
			}
			fdate = fdate.toString().replace('T', ' ').replace(/\-/g, '/');
			var fTime, fStr = 'ymdhis';
			if (!formatStr)
				formatStr = "y-m-d h:i:s";
			if (fdate)
				fTime = new Date(fdate);
			else
				fTime = new Date();
			var month = fTime.getMonth() + 1;
			var day = fTime.getDate();
			var hours = fTime.getHours();
			var minu = fTime.getMinutes();
			var second = fTime.getSeconds();
			month = month < 10 ? '0' + month : month;
			day = day < 10 ? '0' + day : day;
			hours = hours < 10 ? ('0' + hours) : hours;
			minu = minu < 10 ? '0' + minu : minu;
			second = second < 10 ? '0' + second : second;
			var formatArr = [
				fTime.getFullYear().toString(),
				month.toString(),
				day.toString(),
				hours.toString(),
				minu.toString(),
				second.toString()
			]
			for (var i = 0; i < formatArr.length; i++) {
				formatStr = formatStr.replace(fStr.charAt(i), formatArr[i]);
			}
			return formatStr;
		} else {
			return "";
		}
	},

	getDay: function(num, str) { //获取num后的日期，-1为昨天，1为明天,str为日期间的分隔符一般为'/'或者'-'
		var today = new Date();
		var nowTime = today.getTime();
		var ms = 24 * 3600 * 1000 * num;
		today.setTime(parseInt(nowTime + ms));
		var oYear = today.getFullYear();
		var oMoth = (today.getMonth() + 1).toString();
		if (oMoth.length <= 1) oMoth = '0' + oMoth;
		var oDay = today.getDate().toString();
		if (oDay.length <= 1) oDay = '0' + oDay;
		return oYear + str + oMoth + str + oDay;
	},

	// 判断日期是否是今天
	isToday: function(date) {
		return date.toISOString().slice(0, 10) === new Date().toISOString().slice(0, 10)
	},

	// 秒数转换为 hh:mm:ss 格式
	formatSeconds(s) {
		return new Date(s * 1000).toISOString().substr(11, 8)
	},

	async sleep(t) {
		return new Promise((resolve) => setTimeout(resolve, t));
	},

	//只执行一次函数
	onceFunction(fn) {
		let onceFlag = false
		return function() {
			if (!onceFlag) {
				onceFlag = true
				fn.apply(this, arguments)
			}
		}
	},

	/**
	 * 手机号隐藏中间四位
	 * @param {Object} mobile
	 */
	encryptionMobile: function(mobile) {
		mobile = "" + mobile;
		var reg = /(\d{3})\d{4}(\d{4})/;
		var tel1 = mobile.replace(reg, "$1****$2")
		return tel1;
	},

	// 比较2个或多个对象键值对是否相等
	isEqual: function(...objects) {
		let obj = objects.every(obj => JSON.stringify(obj) === JSON.stringify(objects[0]))
		return obj
	},

	// z-paging上一页刷新
	backReload(num) {
		let pages = getCurrentPages();
		let beforePage = pages[pages.length - num];
		console.log('beforePagebeforePage', beforePage);
		beforePage.$vm.$refs.paging.reload()
	},

	// 预览
	previewImg(list, index) {
		console.log('预览');
		console.log(list);
		console.log(index);
		uni.previewImage({
			current: index,
			urls: list
		})
	}
}

const content = {
	isLogin: utils.isLogin,
	isNullOrEmpty: utils.isNullOrEmpty,
	trim: utils.trim,
	isMobile: utils.isMobile,
	isFloat: utils.isFloat,
	isNum: utils.isNum,
	checkPwd: utils.checkPwd,
	formatNum: utils.formatNum,
	rmoney: utils.rmoney,
	formatDate: utils.formatDate,
	formatFullTime: utils.formatFullTime,
	formatMsgTime: utils.formatMsgTime,
	encryptionMobile: utils.encryptionMobile,
	isUserName: utils.isUserName,
	isCardNo: utils.isCardNo,
	isPassword: utils.isPassword,
	getCurrentDate: utils.getCurrentDate,
	randomNum: utils.randomNum,
	getRandomColor: utils.getRandomColor,
	getDay: utils.getDay,
	isToday: utils.isToday,
	formatSeconds: utils.formatSeconds,
	isEqual: utils.isEqual,
	sleep: utils.sleep,
	onceFunction: utils.onceFunction,
	backReload: utils.backReload,
	previewImg: utils.previewImg,
	isHide: utils.isHide,
}

export default content